// 轮番图管理脚本
class CarouselManager {
    constructor() {
        this.carouselImages = [];
        this.currentCarouselPage = 1;
        this.carouselLimit = 10;
        this.userClientPath = '/workspace/NodeJS/008/project/user-client/public/tp/';
    }

    // 初始化轮番图管理器
    async init() {
        await this.loadCarouselImages();
        this.setupCarouselEventListeners();
        this.renderCarouselGrid();
    }

    // 加载轮番图数据
    async loadCarouselImages() {
        try {
            // 从后端API获取轮番图数据
            const response = await apiClient.get('/gallery/usage/carousel');
            if (response.success) {
                this.carouselImages = response.data;
            } else {
                // 如果API不可用，扫描本地文件
                await this.scanLocalCarouselImages();
            }
        } catch (error) {
            console.warn('API获取轮番图失败，使用本地扫描:', error);
            await this.scanLocalCarouselImages();
        }
    }

    // 扫描本地轮番图文件
    async scanLocalCarouselImages() {
        try {
            // 这里应该通过后端API扫描文件，暂时使用模拟数据
            this.carouselImages = [
                {
                    id: 1,
                    name: '轮番图.jpg',
                    image_url: '/static/tp/轮番图.jpg',
                    description: '用户端轮播图',
                    fileSize: 564450,
                    dimensions: '1920x1080',
                    usageType: 'carousel',
                    isActive: true,
                    sortOrder: 1
                },
                {
                    id: 2,
                    name: '轮番图1.jpg',
                    image_url: '/static/tp/轮番图1.jpg',
                    description: '用户端轮播图',
                    fileSize: 779040,
                    dimensions: '1920x1080',
                    usageType: 'carousel',
                    isActive: true,
                    sortOrder: 2
                }
            ];
        } catch (error) {
            console.error('扫描本地轮番图失败:', error);
        }
    }

    // 设置轮番图事件监听器
    setupCarouselEventListeners() {
        // 轮番图排序事件
        document.addEventListener('click', (e) => {
            if (e.target.classList.contains('carousel-sort-up')) {
                this.moveCarouselImageUp(parseInt(e.target.dataset.id));
            } else if (e.target.classList.contains('carousel-sort-down')) {
                this.moveCarouselImageDown(parseInt(e.target.dataset.id));
            }
        });

        // 轮番图预览事件
        document.addEventListener('click', (e) => {
            if (e.target.classList.contains('carousel-preview')) {
                this.previewCarouselImage(parseInt(e.target.dataset.id));
            }
        });
    }

    // 渲染轮番图网格
    renderCarouselGrid() {
        const carouselGrid = document.getElementById('carouselGrid');
        
        if (!carouselGrid) return;

        if (this.carouselImages.length === 0) {
            carouselGrid.innerHTML = `
                <div class="empty-state">
                    <i class="fas fa-images" style="font-size: 4rem; color: #bdc3c7; margin-bottom: 20px;"></i>
                    <h3>暂无轮番图</h3>
                    <p>点击"上传轮番图"按钮开始添加轮播图片</p>
                    <button class="btn-primary" onclick="showCarouselUploadModal()">
                        <i class="fas fa-upload"></i> 上传轮番图
                    </button>
                </div>
            `;
            return;
        }

        carouselGrid.innerHTML = this.carouselImages.map((image, index) => 
            this.createCarouselCard(image, index)
        ).join('');
    }

    // 创建轮番图卡片
    createCarouselCard(image, index) {
        const fileSize = this.formatFileSize(image.fileSize);
        
        return `
            <div class="carousel-card" data-id="${image.id}">
                <div class="carousel-preview-container">
                    <img src="${image.image_url}" alt="${image.name}" 
                         class="carousel-preview" data-id="${image.id}"
                         onerror="this.src='../assets/images/placeholder.jpg'">
                    <div class="carousel-badge">轮播图 ${index + 1}</div>
                    <div class="carousel-status ${image.isActive ? 'active' : 'inactive'}">
                        ${image.isActive ? '已启用' : '已禁用'}
                    </div>
                </div>
                <div class="carousel-info">
                    <div class="carousel-name" title="${image.name}">${image.name}</div>
                    ${image.description ? `<div class="carousel-description">${image.description}</div>` : ''}
                    <div class="carousel-meta">
                        <span>${fileSize}</span>
                        <span>${image.dimensions || '未知尺寸'}</span>
                    </div>
                    <div class="carousel-actions">
                        <button class="btn-small btn-sort-up carousel-sort-up" data-id="${image.id}" 
                                ${index === 0 ? 'disabled' : ''}>
                            <i class="fas fa-arrow-up"></i> 上移
                        </button>
                        <button class="btn-small btn-sort-down carousel-sort-down" data-id="${image.id}" 
                                ${index === this.carouselImages.length - 1 ? 'disabled' : ''}>
                            <i class="fas fa-arrow-down"></i> 下移
                        </button>
                        <button class="btn-small btn-edit" onclick="editCarouselImage(${image.id})">
                            <i class="fas fa-edit"></i> 编辑
                        </button>
                        <button class="btn-small btn-delete" onclick="deleteCarouselImageConfirm(${image.id})">
                            <i class="fas fa-trash"></i> 删除
                        </button>
                    </div>
                </div>
            </div>
        `;
    }

    // 上移轮番图
    async moveCarouselImageUp(imageId) {
        const index = this.carouselImages.findIndex(img => img.id === imageId);
        if (index > 0) {
            // 交换位置
            [this.carouselImages[index], this.carouselImages[index - 1]] = 
            [this.carouselImages[index - 1], this.carouselImages[index]];
            
            await this.updateCarouselSortOrder();
            this.renderCarouselGrid();
        }
    }

    // 下移轮番图
    async moveCarouselImageDown(imageId) {
        const index = this.carouselImages.findIndex(img => img.id === imageId);
        if (index < this.carouselImages.length - 1) {
            // 交换位置
            [this.carouselImages[index], this.carouselImages[index + 1]] = 
            [this.carouselImages[index + 1], this.carouselImages[index]];
            
            await this.updateCarouselSortOrder();
            this.renderCarouselGrid();
        }
    }

    // 更新轮番图排序
    async updateCarouselSortOrder() {
        try {
            const sortData = this.carouselImages.map((image, index) => ({
                id: image.id,
                sortOrder: index + 1
            }));

            await apiClient.post('/gallery/sort', { sortData });
        } catch (error) {
            console.error('更新轮番图排序失败:', error);
        }
    }

    // 预览轮番图
    previewCarouselImage(imageId) {
        const image = this.carouselImages.find(img => img.id === imageId);
        if (image) {
            // 显示大图预览模态框
            showCarouselPreviewModal(image);
        }
    }

    // 格式化文件大小
    formatFileSize(bytes) {
        if (!bytes) return '未知大小';
        
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        if (bytes === 0) return '0 Bytes';
        
        const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
        return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i];
    }
}

// 图库管理脚本
class GalleryManager {
    constructor() {
        this.currentPage = 1;
        this.limit = 20;
        this.totalPages = 0;
        this.totalItems = 0;
        this.filters = {
            category: '',
            usageType: '',
            status: '',
            search: ''
        };
        this.galleryData = [];
        this.statsData = {};
        
        // 初始化轮番图管理器
        this.carouselManager = new CarouselManager();
    }

    // 初始化图库管理器
    init() {
        this.loadGalleryStats();
        this.loadGalleryData();
        this.setupEventListeners();
        
        // 初始化轮番图管理器
        this.carouselManager.init();
    }

    // 设置事件监听器
    setupEventListeners() {
        // 键盘快捷键
        document.addEventListener('keydown', (e) => {
            if (e.ctrlKey && e.key === 'u') {
                e.preventDefault();
                showUploadModal();
            }
        });

        // 窗口大小变化时重新布局
        window.addEventListener('resize', this.handleResize.bind(this));
    }

    // 处理窗口大小变化
    handleResize() {
        // 可以根据窗口大小调整网格布局
        const galleryGrid = document.getElementById('galleryGrid');
        if (window.innerWidth < 768) {
            galleryGrid.style.gridTemplateColumns = '1fr';
        } else if (window.innerWidth < 1200) {
            galleryGrid.style.gridTemplateColumns = 'repeat(auto-fill, minmax(250px, 1fr))';
        } else {
            galleryGrid.style.gridTemplateColumns = 'repeat(auto-fill, minmax(280px, 1fr))';
        }
    }

    // 加载图库统计数据
    async loadGalleryStats() {
        try {
            // 获取分类统计
            const categoryResponse = await apiClient.get('/gallery/stats/categories');
            if (categoryResponse.success) {
                this.statsData.categories = categoryResponse.data;
            }

            // 获取使用统计
            const usageResponse = await apiClient.get('/gallery/stats/usage');
            if (usageResponse.success) {
                this.statsData.usage = usageResponse.data;
            }

            this.updateStatsDisplay();
        } catch (error) {
            console.error('加载统计数据失败:', error);
        }
    }

    // 更新统计显示
    updateStatsDisplay() {
        // 计算总数
        const totalImages = this.statsData.categories?.reduce((sum, item) => sum + parseInt(item.count), 0) || 0;
        const carouselImages = this.statsData.usage?.find(item => item.usage_type === 'carousel')?.count || 0;
        const featuredImages = this.statsData.usage?.find(item => item.usage_type === 'featured')?.count || 0;
        const activeImages = this.statsData.categories?.reduce((sum, item) => sum + parseInt(item.active_count), 0) || 0;

        document.getElementById('totalImages').textContent = totalImages;
        document.getElementById('carouselImages').textContent = carouselImages;
        document.getElementById('featuredImages').textContent = featuredImages;
        document.getElementById('activeImages').textContent = activeImages;
    }

    // 加载图库数据
    async loadGalleryData() {
        this.showLoading();

        try {
            const params = new URLSearchParams({
                page: this.currentPage,
                limit: this.limit
            });

            // 添加筛选条件
            if (this.filters.category) params.append('category', this.filters.category);
            if (this.filters.usageType) params.append('usageType', this.filters.usageType);
            if (this.filters.status) params.append('isActive', this.filters.status === 'active');
            if (this.filters.search) params.append('search', this.filters.search);

            const response = await apiClient.get(`/gallery?${params}`);
            
            if (response.success) {
                this.galleryData = response.data;
                this.totalPages = response.pagination?.totalPages || 1;
                this.totalItems = response.pagination?.total || 0;
                
                this.renderGalleryGrid();
                this.renderPagination();
            } else {
                throw new Error(response.message);
            }
        } catch (error) {
            console.error('加载图库数据失败:', error);
            this.showError('加载图库数据失败，请稍后重试');
        } finally {
            this.hideLoading();
        }
    }

    // 渲染图片网格
    renderGalleryGrid() {
        const galleryGrid = document.getElementById('galleryGrid');
        
        if (this.galleryData.length === 0) {
            galleryGrid.innerHTML = `
                <div class="empty-state">
                    <i class="fas fa-images" style="font-size: 4rem; color: #bdc3c7; margin-bottom: 20px;"></i>
                    <h3>暂无图片</h3>
                    <p>点击"上传图片"按钮开始添加图片到图库</p>
                    <button class="btn-primary" onclick="showUploadModal()">
                        <i class="fas fa-upload"></i> 上传图片
                    </button>
                </div>
            `;
            return;
        }

        galleryGrid.innerHTML = this.galleryData.map(image => this.createImageCard(image)).join('');
    }

    // 创建图片卡片HTML
    createImageCard(image) {
        const usageTypeLabels = {
            'carousel': '轮播图',
            'featured': '首页精选',
            'about': '关于我们',
            'blog': '博客创作',
            'product': '产品管理',
            'general': '通用图片'
        };

        const fileSize = this.formatFileSize(image.fileSize);
        const tags = Array.isArray(image.tags) ? image.tags : [];

        return `
            <div class="image-card" data-id="${image.id}">
                <div class="image-preview">
                    <img src="${image.image_url || image.imageUrl}" alt="${image.name}" 
                         onerror="this.src='../assets/images/placeholder.jpg'">
                    <div class="image-badge">${usageTypeLabels[image.usage_type || image.usageType] || '通用'}</div>
                    <div class="image-status ${image.is_active || image.isActive ? 'active' : ''}">
                        ${image.is_active || image.isActive ? '已启用' : '已禁用'}
                    </div>
                </div>
                <div class="image-info">
                    <div class="image-name" title="${image.name}">${image.name}</div>
                    ${image.description ? `<div class="image-description">${image.description}</div>` : ''}
                    <div class="image-meta">
                        <span>${fileSize}</span>
                        <span>${image.dimensions || '未知尺寸'}</span>
                    </div>
                    ${tags.length > 0 ? `
                        <div class="image-tags">
                            ${tags.slice(0, 3).map(tag => `<span class="tag">${tag}</span>`).join('')}
                            ${tags.length > 3 ? `<span class="tag">+${tags.length - 3}</span>` : ''}
                        </div>
                    ` : ''}
                    <div class="image-actions">
                        <button class="btn-small btn-edit" onclick="editImage(${image.id})">
                            <i class="fas fa-edit"></i> 编辑
                        </button>
                        <button class="btn-small btn-delete" onclick="deleteImageConfirm(${image.id})">
                            <i class="fas fa-trash"></i> 删除
                        </button>
                    </div>
                </div>
            </div>
        `;
    }

    // 格式化文件大小
    formatFileSize(bytes) {
        if (!bytes) return '未知大小';
        
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        if (bytes === 0) return '0 Bytes';
        
        const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
        return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i];
    }

    // 渲染分页控件
    renderPagination() {
        const pagination = document.getElementById('pagination');
        
        if (this.totalPages <= 1) {
            pagination.innerHTML = '';
            return;
        }

        let paginationHTML = '';

        // 上一页按钮
        paginationHTML += `
            <button onclick="galleryManager.goToPage(${this.currentPage - 1})" 
                    ${this.currentPage === 1 ? 'disabled' : ''}>
                <i class="fas fa-chevron-left"></i>
            </button>
        `;

        // 页码按钮
        const startPage = Math.max(1, this.currentPage - 2);
        const endPage = Math.min(this.totalPages, startPage + 4);

        for (let i = startPage; i <= endPage; i++) {
            paginationHTML += `
                <button onclick="galleryManager.goToPage(${i})" 
                        class="${i === this.currentPage ? 'active' : ''}">
                    ${i}
                </button>
            `;
        }

        // 下一页按钮
        paginationHTML += `
            <button onclick="galleryManager.goToPage(${this.currentPage + 1})" 
                    ${this.currentPage === this.totalPages ? 'disabled' : ''}>
                <i class="fas fa-chevron-right"></i>
            </button>
        `;

        // 页面信息
        paginationHTML += `
            <span style="margin-left: 15px; color: #7f8c8d;">
                共 ${this.totalItems} 张图片
            </span>
        `;

        pagination.innerHTML = paginationHTML;
    }

    // 跳转到指定页面
    goToPage(page) {
        if (page < 1 || page > this.totalPages || page === this.currentPage) {
            return;
        }

        this.currentPage = page;
        this.loadGalleryData();
    }

    // 应用筛选条件
    applyFilters() {
        this.currentPage = 1;
        this.loadGalleryData();
    }

    // 显示加载状态
    showLoading() {
        document.getElementById('loadingOverlay').style.display = 'flex';
    }

    // 隐藏加载状态
    hideLoading() {
        document.getElementById('loadingOverlay').style.display = 'none';
    }

    // 显示错误信息
    showError(message) {
        // 可以使用更优雅的错误提示方式
        alert(message);
    }
}

// 全局图库管理器实例
const galleryManager = new GalleryManager();

// 文件上传相关功能
function setupFileUpload() {
    const fileUploadArea = document.getElementById('fileUploadArea');
    const fileInput = document.getElementById('imageFile');
    const fileList = document.getElementById('fileList');
    let selectedFiles = [];

    // 拖拽事件
    fileUploadArea.addEventListener('dragover', (e) => {
        e.preventDefault();
        fileUploadArea.classList.add('dragover');
    });

    fileUploadArea.addEventListener('dragleave', (e) => {
        e.preventDefault();
        fileUploadArea.classList.remove('dragover');
    });

    fileUploadArea.addEventListener('drop', (e) => {
        e.preventDefault();
        fileUploadArea.classList.remove('dragover');
        
        const files = Array.from(e.dataTransfer.files);
        handleFiles(files);
    });

    // 点击事件
    fileUploadArea.addEventListener('click', () => {
        fileInput.click();
    });

    // 文件选择事件
    fileInput.addEventListener('change', (e) => {
        const files = Array.from(e.target.files);
        handleFiles(files);
    });

    // 处理选择的文件
    function handleFiles(files) {
        const imageFiles = files.filter(file => file.type.startsWith('image/'));
        
        if (imageFiles.length === 0) {
            alert('请选择图片文件');
            return;
        }

        selectedFiles = [...selectedFiles, ...imageFiles];
        renderFileList();
    }

    // 渲染文件列表
    function renderFileList() {
        fileList.innerHTML = selectedFiles.map((file, index) => `
            <div class="file-item">
                <div class="file-info">
                    <i class="fas fa-image"></i>
                    <span>${file.name} (${formatFileSize(file.size)})</span>
                </div>
                <button class="file-remove" onclick="removeFile(${index})">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        `).join('');
    }

    // 移除文件
    window.removeFile = function(index) {
        selectedFiles.splice(index, 1);
        renderFileList();
    };

    // 格式化文件大小
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
        return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i];
    }

    // 保存文件列表到全局变量
    window.selectedFiles = selectedFiles;
}

// 模态框控制函数
function showUploadModal() {
    document.getElementById('uploadModal').style.display = 'block';
    document.getElementById('uploadForm').reset();
    document.getElementById('fileList').innerHTML = '';
    window.selectedFiles = [];
}

function closeUploadModal() {
    document.getElementById('uploadModal').style.display = 'none';
}

// 轮番图管理函数
function showCarouselUploadModal() {
    document.getElementById('carouselUploadModal').style.display = 'block';
    document.getElementById('carouselUploadForm').reset();
    document.getElementById('carouselFileList').innerHTML = '';
    window.selectedCarouselFiles = [];
}

function closeCarouselUploadModal() {
    document.getElementById('carouselUploadModal').style.display = 'none';
}

function showCarouselPreviewModal(image) {
    const modal = document.getElementById('carouselPreviewModal');
    const previewImg = document.getElementById('carouselPreviewImg');
    const previewInfo = document.getElementById('carouselPreviewInfo');
    
    previewImg.src = image.image_url;
    previewInfo.innerHTML = `
        <h3>${image.name}</h3>
        <p><strong>描述:</strong> ${image.description || '无描述'}</p>
        <p><strong>文件大小:</strong> ${galleryManager.carouselManager.formatFileSize(image.fileSize)}</p>
        <p><strong>尺寸:</strong> ${image.dimensions || '未知'}</p>
        <p><strong>状态:</strong> ${image.isActive ? '已启用' : '已禁用'}</p>
    `;
    
    modal.style.display = 'block';
}

function closeCarouselPreviewModal() {
    document.getElementById('carouselPreviewModal').style.display = 'none';
}

async function editCarouselImage(imageId) {
    try {
        const image = galleryManager.carouselManager.carouselImages.find(img => img.id === imageId);
        if (image) {
            document.getElementById('editCarouselImageId').value = image.id;
            document.getElementById('editCarouselImageUrl').src = image.image_url;
            document.getElementById('editCarouselImageName').value = image.name;
            document.getElementById('editCarouselImageDescription').value = image.description || '';
            document.getElementById('editCarouselImageActive').checked = image.isActive;
            
            document.getElementById('editCarouselModal').style.display = 'block';
        }
    } catch (error) {
        console.error('编辑轮番图失败:', error);
        alert('编辑轮番图失败');
    }
}

function closeEditCarouselModal() {
    document.getElementById('editCarouselModal').style.display = 'none';
}

async function saveCarouselChanges() {
    const imageId = document.getElementById('editCarouselImageId').value;
    
    if (!imageId) {
        alert('轮番图ID无效');
        return;
    }

    const updateData = {
        name: document.getElementById('editCarouselImageName').value,
        description: document.getElementById('editCarouselImageDescription').value,
        isActive: document.getElementById('editCarouselImageActive').checked
    };

    try {
        // 这里应该调用API更新轮番图
        const response = await apiClient.put(`/gallery/${imageId}`, updateData);
        
        if (response.success) {
            alert('轮番图更新成功！');
            closeEditCarouselModal();
            await galleryManager.carouselManager.loadCarouselImages();
            galleryManager.carouselManager.renderCarouselGrid();
        } else {
            throw new Error(response.message);
        }
    } catch (error) {
        console.error('更新轮番图失败:', error);
        alert('更新轮番图失败: ' + error.message);
    }
}

function deleteCarouselImageConfirm(imageId) {
    if (confirm('确定要删除这张轮番图吗？此操作不可恢复。')) {
        deleteCarouselImage(imageId);
    }
}

async function deleteCarouselImage(imageId) {
    try {
        const response = await apiClient.delete(`/gallery/${imageId}`);
        
        if (response.success) {
            alert('轮番图删除成功！');
            await galleryManager.carouselManager.loadCarouselImages();
            galleryManager.carouselManager.renderCarouselGrid();
        } else {
            throw new Error(response.message);
        }
    } catch (error) {
        console.error('删除轮番图失败:', error);
        alert('删除轮番图失败: ' + error.message);
    }
}

// 设置轮番图文件上传
function setupCarouselFileUpload() {
    const fileUploadArea = document.getElementById('carouselFileUploadArea');
    const fileInput = document.getElementById('carouselImageFile');
    const fileList = document.getElementById('carouselFileList');
    let selectedFiles = [];

    // 拖拽事件
    fileUploadArea.addEventListener('dragover', (e) => {
        e.preventDefault();
        fileUploadArea.classList.add('dragover');
    });

    fileUploadArea.addEventListener('dragleave', (e) => {
        e.preventDefault();
        fileUploadArea.classList.remove('dragover');
    });

    fileUploadArea.addEventListener('drop', (e) => {
        e.preventDefault();
        fileUploadArea.classList.remove('dragover');
        
        const files = Array.from(e.dataTransfer.files);
        handleFiles(files);
    });

    // 点击事件
    fileUploadArea.addEventListener('click', () => {
        fileInput.click();
    });

    // 文件选择事件
    fileInput.addEventListener('change', (e) => {
        const files = Array.from(e.target.files);
        handleFiles(files);
    });

    // 处理选择的文件
    function handleFiles(files) {
        const imageFiles = files.filter(file => file.type.startsWith('image/'));
        
        if (imageFiles.length === 0) {
            alert('请选择图片文件');
            return;
        }

        selectedFiles = [...selectedFiles, ...imageFiles];
        renderFileList();
    }

    // 渲染文件列表
    function renderFileList() {
        fileList.innerHTML = selectedFiles.map((file, index) => `
            <div class="file-item">
                <div class="file-info">
                    <i class="fas fa-image"></i>
                    <span>${file.name} (${formatFileSize(file.size)})</span>
                </div>
                <button class="file-remove" onclick="removeCarouselFile(${index})">
                    <i class="fas fa-times"></i>
                </button>
            </div>
        `).join('');
    }

    // 移除文件
    window.removeCarouselFile = function(index) {
        selectedFiles.splice(index, 1);
        renderFileList();
    };

    // 格式化文件大小
    function formatFileSize(bytes) {
        if (bytes === 0) return '0 Bytes';
        const sizes = ['Bytes', 'KB', 'MB', 'GB'];
        const i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
        return Math.round(bytes / Math.pow(1024, i) * 100) / 100 + ' ' + sizes[i];
    }

    // 保存文件列表到全局变量
    window.selectedCarouselFiles = selectedFiles;
}

// 上传轮番图
async function uploadCarouselImages() {
    if (window.selectedCarouselFiles.length === 0) {
        alert('请选择要上传的轮番图文件');
        return;
    }

    const imageName = document.getElementById('carouselImageName').value;
    if (!imageName) {
        alert('请输入轮番图名称');
        return;
    }

    try {
        const uploadData = {
            name: imageName,
            description: document.getElementById('carouselImageDescription').value,
            usageType: 'carousel',
            isActive: document.getElementById('carouselImageActive').checked
        };

        // 模拟上传每个文件
        for (const file of window.selectedCarouselFiles) {
            const mockUploadResult = {
                imageUrl: `/static/tp/${file.name}`,
                thumbnailUrl: `/static/tp/thumbnails/${file.name}`,
                fileSize: file.size,
                fileType: file.type,
                dimensions: '1920x1080'
            };

            const galleryData = {
                ...uploadData,
                ...mockUploadResult
            };

            const response = await apiClient.post('/gallery', galleryData);
            
            if (!response.success) {
                throw new Error(response.message);
            }
        }

        alert('轮番图上传成功！');
        closeCarouselUploadModal();
        await galleryManager.carouselManager.loadCarouselImages();
        galleryManager.carouselManager.renderCarouselGrid();

    } catch (error) {
        console.error('上传轮番图失败:', error);
        alert('上传轮番图失败: ' + error.message);
    }
}

// 全局函数导出
window.galleryManager = galleryManager;
window.showUploadModal = showUploadModal;
window.closeUploadModal = closeUploadModal;
window.showStatsModal = showStatsModal;
window.closeStatsModal = closeStatsModal;
window.filterGallery = filterGallery;
window.editImage = editImage;
window.deleteImageConfirm = deleteImageConfirm;
window.deleteImage = deleteImage;

// 轮番图管理函数导出
window.showCarouselUploadModal = showCarouselUploadModal;
window.closeCarouselUploadModal = closeCarouselUploadModal;
window.showCarouselPreviewModal = showCarouselPreviewModal;
window.closeCarouselPreviewModal = closeCarouselPreviewModal;
window.editCarouselImage = editCarouselImage;
window.closeEditCarouselModal = closeEditCarouselModal;
window.saveCarouselChanges = saveCarouselChanges;
window.deleteCarouselImageConfirm = deleteCarouselImageConfirm;
window.deleteCarouselImage = deleteCarouselImage;
window.uploadCarouselImages = uploadCarouselImages;

// 初始化轮番图文件上传
setupCarouselFileUpload();

function showEditModal() {
    document.getElementById('editModal').style.display = 'block';
}

function closeEditModal() {
    document.getElementById('editModal').style.display = 'none';
}

function showStatsModal() {
    document.getElementById('statsModal').style.display = 'block';
    renderStatsCharts();
}

function closeStatsModal() {
    document.getElementById('statsModal').style.display = 'none';
}

// 渲染统计图表
function renderStatsCharts() {
    // 这里可以集成图表库，暂时用简单的HTML展示
    const categoryStats = document.getElementById('categoryStats');
    const usageStats = document.getElementById('usageStats');

    if (galleryManager.statsData.categories) {
        categoryStats.innerHTML = galleryManager.statsData.categories.map(stat => 
            `<div>${stat.category || '未分类'}: ${stat.count}张 (${stat.active_count}张活跃)</div>`
        ).join('');
    }

    if (galleryManager.statsData.usage) {
        usageStats.innerHTML = galleryManager.statsData.usage.map(stat => 
            `<div>${getUsageTypeLabel(stat.usage_type)}: ${stat.count}张</div>`
        ).join('');
    }
}

// 获取用途类型标签
function getUsageTypeLabel(usageType) {
    const labels = {
        'carousel': '轮播图',
        'featured': '首页精选',
        'about': '关于我们',
        'blog': '博客创作',
        'product': '产品管理',
        'general': '通用图片'
    };
    return labels[usageType] || usageType;
}

// 筛选图库
function filterGallery() {
    galleryManager.filters.category = document.getElementById('categoryFilter').value;
    galleryManager.filters.usageType = document.getElementById('usageTypeFilter').value;
    galleryManager.filters.status = document.getElementById('statusFilter').value;
    galleryManager.filters.search = document.getElementById('searchInput').value;
    
    galleryManager.applyFilters();
}

// 上传图片
async function uploadImages() {
    if (window.selectedFiles.length === 0) {
        alert('请选择要上传的图片文件');
        return;
    }

    const imageName = document.getElementById('imageName').value;
    if (!imageName) {
        alert('请输入图片名称');
        return;
    }

    try {
        // 这里应该实现实际的文件上传逻辑
        // 目前使用模拟上传
        
        const uploadData = {
            name: imageName,
            description: document.getElementById('imageDescription').value,
            category: document.getElementById('imageCategory').value,
            usageType: document.getElementById('imageUsageType').value,
            tags: document.getElementById('imageTags').value.split(',').map(tag => tag.trim()).filter(tag => tag),
            isActive: document.getElementById('imageActive').checked
        };

        // 模拟上传每个文件
        for (const file of window.selectedFiles) {
            // 模拟文件处理结果
            const mockUploadResult = {
                imageUrl: `/uploads/images/${file.name}`,
                thumbnailUrl: `/uploads/thumbnails/${file.name}`,
                fileSize: file.size,
                fileType: file.type,
                dimensions: '1920x1080' // 模拟尺寸
            };

            const galleryData = {
                ...uploadData,
                ...mockUploadResult
            };

            const response = await apiClient.post('/gallery', galleryData);
            
            if (!response.success) {
                throw new Error(response.message);
            }
        }

        alert('图片上传成功！');
        closeUploadModal();
        galleryManager.loadGalleryData();
        galleryManager.loadGalleryStats();

    } catch (error) {
        console.error('上传图片失败:', error);
        alert('上传图片失败: ' + error.message);
    }
}

// 编辑图片
async function editImage(imageId) {
    try {
        const response = await apiClient.get(`/gallery/${imageId}`);
        
        if (response.success) {
            const image = response.data;
            
            document.getElementById('editImageId').value = image.id;
            document.getElementById('editImageUrl').src = image.image_url || image.imageUrl;
            document.getElementById('editImageName').value = image.name;
            document.getElementById('editImageDescription').value = image.description || '';
            document.getElementById('editImageCategory').value = image.category || '';
            document.getElementById('editImageUsageType').value = image.usage_type || image.usageType || 'general';
            document.getElementById('editImageTags').value = Array.isArray(image.tags) ? image.tags.join(', ') : '';
            document.getElementById('editImageSortOrder').value = image.sort_order || image.sortOrder || 0;
            document.getElementById('editImageActive').checked = image.is_active || image.isActive;
            
            showEditModal();
        } else {
            throw new Error(response.message);
        }
    } catch (error) {
        console.error('获取图片详情失败:', error);
        alert('获取图片详情失败');
    }
}

// 保存图片更改
async function saveImageChanges() {
    const imageId = document.getElementById('editImageId').value;
    
    if (!imageId) {
        alert('图片ID无效');
        return;
    }

    const updateData = {
        name: document.getElementById('editImageName').value,
        description: document.getElementById('editImageDescription').value,
        category: document.getElementById('editImageCategory').value,
        usageType: document.getElementById('editImageUsageType').value,
        tags: document.getElementById('editImageTags').value.split(',').map(tag => tag.trim()).filter(tag => tag),
        sortOrder: parseInt(document.getElementById('editImageSortOrder').value) || 0,
        isActive: document.getElementById('editImageActive').checked
    };

    try {
        const response = await apiClient.put(`/gallery/${imageId}`, updateData);
        
        if (response.success) {
            alert('图片更新成功！');
            closeEditModal();
            galleryManager.loadGalleryData();
            galleryManager.loadGalleryStats();
        } else {
            throw new Error(response.message);
        }
    } catch (error) {
        console.error('更新图片失败:', error);
        alert('更新图片失败: ' + error.message);
    }
}

// 删除图片确认
function deleteImageConfirm(imageId) {
    if (confirm('确定要删除这张图片吗？此操作不可恢复。')) {
        deleteImage(imageId);
    }
}

// 删除图片
async function deleteImage(imageId) {
    try {
        const response = await apiClient.delete(`/gallery/${imageId}`);
        
        if (response.success) {
            alert('图片删除成功！');
            galleryManager.loadGalleryData();
            galleryManager.loadGalleryStats();
            closeEditModal();
        } else {
            throw new Error(response.message);
        }
    } catch (error) {
        console.error('删除图片失败:', error);
        alert('删除图片失败: ' + error.message);
    }
}

// 全局函数导出
window.galleryManager = galleryManager;
window.showUploadModal = showUploadModal;
window.closeUploadModal = closeUploadModal;
window.showStatsModal = showStatsModal;
window.closeStatsModal = closeStatsModal;
window.filterGallery = filterGallery;
window.editImage = editImage;
window.deleteImageConfirm = deleteImageConfirm;
window.deleteImage = deleteImage;